import Config from './config.js'
import { getToken, setToken, removeToken, refreshToken } from '@/common/auth'
import { inArray } from '@/common/common';
async function request(option) 
{
	if (option.name) {
		option.url  = Config.url[option.name]
	}
	if(option.suffix){
		option.url = option.url + option.suffix
	}
	option.header = {
		'Content-Type':'application/x-www-form-urlencoded',
	}
	
	if (option.name == 'product.index' || option.name == 'product.detail') {
		let location = uni.getStorageSync('location')
		if (location && location.latitude && location.longitude) {
			option.url += "?latitude=" + location.latitude
			option.url += "&longitude=" + location.longitude
		} else {
			option.url += "?latitude=" + 23.731
			option.url += "&longitude=" + 113.211
		}
	}
	console.log(option);
	//过期，即先拦截 ，刷新token后，再继续请求
	//authorizations/current
	var token = getToken();
	if(option.name != 'user.login' && option.name != 'user.register'){
		var tmpToken = await refreshToken();
		if(tmpToken){
			token = tmpToken;
		}
	}
	console.log('token : ', token)
	if(token){
		option.header['Authorization'] = 'Bearer ' + token;
	}else{
		
	}
	var succ_callback = option.success;
	option.success = function(res){
		
		if(res.statusCode && res.statusCode >= 400){
			console.log((res.data.message == 'Token has expired' && token));
			console.log('request error statusCode', option.url, res.statusCode, res);
			if(Config.show_err){
				uni.showModal({
					title: '异常', 
				    content: ''+res.data.message,
					showCancel: false
				});
			}
			if((res.data.message != undefined && res.data.message.indexOf('Token') !== false && token) || ! token){
				//刷新token
				var pages = getCurrentPages();
				var route = (pages[pages.length - 1]).route;
				if(inArray(route, Config.no_authed_pages)){
					return false;
				}
				uni.showModal({
				    content: Config.common_text.login_expired,
					showCancel: false,
					success: function(res){
						uni.navigateTo({
							url: Config.isCourse ? `/pages/course/login?relogin=1` : `/pages/public/login?relogin=1`
						})
					}
				});
			} 
			
		}
		succ_callback(res);
	}
	uni.request(option)
	
}
export default request